import * as React from 'react';
import { Button, SearchBox, IconButton, Modal, Icon } from 'office-ui-fabric-react'
import { Dialog, DialogType, DialogFooter, PrimaryButton, DefaultButton } from 'office-ui-fabric-react'
import HotSearch from '../../components/HotSearch'
import { documentTemplateSearch, documentTemplateGetDetail } from '../../services/documentAssistant'
import { Pagination, ListContainer } from '../../components'
import { openDialog } from '../../utils/WordDialog'
import { replaceDocumentWithOoxml, isSupportWordApi } from '../../utils/WordUtil';

import './styles.less'

var moment = require('moment')

export interface AppProps {

}

export interface AppState {
  keyword?: string,
  listItems: any[],
  hotSearch: string[],
  showHotSearch: boolean,
  pageNo: number,
  pageCount: number,
  documentDetail: object,
  hideDialog: boolean
}

export default class App extends React.Component<AppProps, AppState> {
  constructor(props, context) {
    super(props, context);
    this.state = {
      listItems: [],
      hotSearch: ['人力资源', '总结报告', '制度规范', '市场营销', '合同协议', '研究报告'],
      showHotSearch: true,
      pageNo: 1,
      pageCount: 0,
      documentDetail: {},
      hideDialog: true
    };
  }

  componentWillMount() {
    this.onSearch()
  }

  // 搜索
  onSearch = async () => {
    const queryData = {
      kw: this.state.keyword,
      pageNo: this.state.pageNo,
      pageSize: 10
    }
    const result = await documentTemplateSearch(queryData)
    this.setState({
      listItems: result.data.rsData,
      showHotSearch: this.state.keyword && result.data.rsData && result.data.rsData.length > 0 ? false : true,
      pageCount: result.data.rsCount
    })
  }
  onSearchChange = (value) => {
    this.setState({
      keyword: value
    })
  }
  // 热门搜索
  onSelectTag = (value) => {
    this.setState({
      keyword: value
    }, () => { this.onSearch() })
  }

  // 清空搜素
  clearSearch = () => {
    this.setState({
      keyword: '',
      listItems: [],
      showHotSearch: true,
      pageCount: 0,
      pageNo: 1
    })
  }


  // 预览
  previewDocument = (id) => {
    try {
      this.dialog.close();
    } catch (err) {
      //
    }
    if (isSupportWordApi()) {
      Word.run(context => {
        var body = context.document.body
        context.load(body, 'text');
        return context.sync().then(() => {
          let isHaveBody = false
          if (body.text) {
            isHaveBody = true
          }
          openDialog(`/documentTemplateDialog?id=${id}&isHaveBody=${isHaveBody}`, this.applyCallback)
        })
      }).catch(function (error) {
        if (error instanceof OfficeExtension.Error) {
          console.log('Debug info: ' + JSON.stringify(error.debugInfo))
        }
      });
    } else {
      openDialog(`/documentTemplateDialog?id=${id}`, this.applyCallback)
    }
  }
  // 获取文档详情
  getDocumentDetail = async (id, showTips) => { // showTips: 文档中有内容则提示用户
    const queryData = { id }
    const result = await documentTemplateGetDetail(queryData)
    this.setState({ documentDetail: result.data }, () => {
      if (isSupportWordApi()) { // 2016
        Word.run(context => {
          var body = context.document.body
          context.load(body, 'text');
          return context.sync().then(() => {
            if (body.text && showTips) {
              this.setState({ hideDialog: false })
            } else {
              this.applyTemplate()
            }
          })
        }).catch(function (error) {
          if (error instanceof OfficeExtension.Error) {
            console.log('Debug info: ' + JSON.stringify(error.debugInfo))
          }
        });
      } else {  // 2013 没有替换功能只能插入 不需要提示
        this.applyTemplate()
      }
    })
  }

  dialog // 赋值打开的弹窗实例
  messageHandler = (arg) => {
    console.info('接收弹窗传送的段落id', arg.message)
    const id = arg.message
    this.getDocumentDetail(id, false)
    this.dialog.close();
  }
  applyCallback = (asyncResult) => {
    if (asyncResult.status == "failed") {
    }
    else {
      this.dialog = asyncResult.value;
      /*Messages are sent by developers programatically from the dialog using office.context.ui.messageParent(...)*/
      this.dialog.addEventHandler(Office.EventType.DialogMessageReceived, this.messageHandler);
      /*Events are sent by the platform in response to user actions or errors. For example, the dialog is closed via the 'x' button*/
      this.dialog.addEventHandler(Office.EventType.DialogEventReceived, arg => console.log(arg));
    }
  }

  closeDialog = () => {
    this.setState({ hideDialog: true })
  }

  // 使用模板
  applyTemplate = () => {
    const { content }: any = this.state.documentDetail
    replaceDocumentWithOoxml(content)
    this.setState({ hideDialog: true })
  }

  // 分页跳转
  onPageChange = (page) => {
    this.setState({
      pageNo: page,
    }, this.onSearch)
  }

  render() {
    const { keyword, hotSearch, pageNo, pageCount, listItems } = this.state
    return (
      <div className='document-container'>
        <SearchBox
          placeholder="输入搜索内容"
          onSearch={this.onSearch}
          onClear={this.clearSearch}
          onChange={this.onSearchChange}
          value={keyword}
        />
        {
          this.state.showHotSearch && <div>
            <div className="hot-title">热门搜索</div>
            <HotSearch list={hotSearch} onSelectTag={this.onSelectTag} />
          </div>
        }
        <ListContainer
          className="list-wrap"
          showContent={listItems.length > 0}
          onPageChange={this.onPageChange}
          current={pageNo}
          total={pageCount}
        >
          {listItems.map((item, index) => {
            return (
              <div className="list" aria-describedby="customID" key={index} onClick={() => { this.previewDocument(item.id) }}>
                {
                  item.icon && <i className={`ms-Icon ms-Icon--WordDocument ${item.icon}`} aria-hidden="true"></i>
                }
                {!item.icon && <i className="ms-Icon ms-Icon--WordDocument word-icon" aria-hidden="true"></i>}
                <div className="content-wrap">
                  <div className="title" title={item.title}>{item.title}</div>
                  <div className="date">{moment(item.lastModifyTime).format('YYYY-MM-DD')}</div>
                </div>
                <div className="dot">
                  <IconButton
                    data-automation-id="test"
                    iconProps={{ iconName: 'More' }}
                    menuProps={{
                      items: [
                        {
                          key: 'view',
                          text: '预览',
                          iconProps: {
                            iconName: 'View',
                          },
                          onClick: () => {
                            this.previewDocument(item.id)
                            return;
                          }
                        },
                        {
                          key: 'download',
                          text: '插入word',
                          iconProps: {
                            iconName: 'Download',
                          },
                          onClick: () => {
                            this.getDocumentDetail(item.id, true)
                            return;
                          }
                        }
                      ]
                    }}
                  />
                </div>
              </div>
            )
          })}
        </ListContainer>

        <Dialog
          hidden={this.state.hideDialog}
          onDismiss={this.closeDialog}
          dialogContentProps={{
            type: DialogType.normal,
            title: '',
            subText:
              '是否确定替换当前模板内容？'
          }}
          modalProps={{
            titleAriaId: 'myLabelId',
            subtitleAriaId: 'mySubTextId',
            isBlocking: false,
            containerClassName: 'ms-dialogMainOverride'
          }}
        >
          <DialogFooter>
            <DefaultButton onClick={this.closeDialog} text="取消" />
            <PrimaryButton onClick={this.applyTemplate} text="确定" />
          </DialogFooter>
        </Dialog>
      </div>
    );
  }
}
